#! /bin/sh

CONFIG="/etc/turnserver.conf"
. /etc/default/turnserver

coturn_start() {
    if [ ! -d $TURN_PID_PATH ]; then
      mkdir -p $TURN_PID_PATH
      chown $TURN_USER:$TURN_GROUP $TURN_PID_PATH
    fi
    if [ -x /usr/bin/turnserver ]; then
      echo "Starting turnserver daemon:  /usr/bin/turnserver"
      su -l -c "/usr/bin/turnserver -o -c $CONFIG --pidfile $TURN_PID_PATH/turnserver.pid" $TURN_USER
    fi
}

coturn_stop() {
    echo "Stopping turnserver daemon:  /usr/bin/turnserver"
    kill $(cat $TURN_PID_PATH/turnserver.pid)
    rm -f $TURN_PID_PATH/turnserver.pid
}

coturn_restart() {
    coturn_stop
    sleep 1
    coturn_start
}

case "$1" in
'start')
    coturn_start
    ;;
'stop')
    coturn_stop
    ;;
'restart')
    coturn_restart
    ;;
*)
    echo "usage $0 start|stop|restart"
esac

exit 0
